package com.webank.utils;



import com.webank.bean.Block;
import com.webank.bean.Record;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by kantlin on 2018/7/26.
 */
public class WriteAndReadBlock {

    /**
     * 写入block
     * @param block
     * @throws Exception
     */
    public static void writeBlock(Block block) throws Exception {
        ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(new File(Contants.FILEPATH+block.getBlockHash())));
        oos1.writeObject(block);

        ObjectOutputStream fos = new ObjectOutputStream(new FileOutputStream(Contants.FILEPATH+"lastPreviousHash"));
        fos.writeObject(block.getBlockHash());
        oos1.close();
        fos.close();
    }

    /**
     * 从block中读取
     * @param vin
     * @throws Exception
     */
    public static List<Record> readBlock(String vin) throws Exception  {
        List<Record> records = new ArrayList<>();
        Object hashCode;
        File file=new File(Contants.FILEPATH + "lastPreviousHash");
        if(file.exists()){
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(Contants.FILEPATH + "lastPreviousHash")));
            hashCode = in.readObject();
        }else{
            return records;
        }
        Block block = readFile(Contants.FILEPATH + hashCode.toString());

        while (block!=null ){
            //previousHash用于进行块验证
            String previousHash = block.getPreviousHash();
            if(readFile(Contants.FILEPATH + block.getBlockHash()).getRecord().getVIN().equals(vin)){
                records.add(readFile(Contants.FILEPATH + block.getBlockHash()).getRecord());
            }
            if(!block.getPreviousHash().equals("")){
                block = readFile(Contants.FILEPATH + block.getPreviousHash());
                if(!previousHash.equals(block.getBlockHash())){
                    return records;
                }
            }else{
                return records;
            }
        }

        return records;
    }
    /**
     * 读取文件
     * @param str
     * @return
     * @throws Exception
     */
    public static Block readFile(String str)throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(str)));
        Block block =(Block) ois.readObject();
        ois.close();
        return block;
    }

}
